package com.smallkingson.ylib.net.download;

import java.util.List;

import android.content.Context;
import android.database.sqlite.SQLiteOpenHelper;

import com.smallkingson.ylib.core.Yr;
import com.smallkingson.ylib.db.YSQLites;
import com.smallkingson.ylib.db.cache.YCacher;
import com.smallkingson.ylib.db.cache.YKey;

public class YDownloadCacher extends YCacher<YKey, DownloadFile> {

	private static YDownloadCacher instance;

	private YDownloadCacher(Context context) {
		init(context);
	};

	public static YDownloadCacher getInstance(Context context) {
		if (instance == null) {
			synchronized (YDownloadCacher.class) {
				if (instance == null) {
					instance = new YDownloadCacher(context);
				}
			}
		}
		return instance;
	}

	@Override
	protected void onInit(SQLiteOpenHelper helper) {
		super.onInit(helper);
		YSQLites.createTable(helper, DownloadFile.class);
	}

	@Override
	public void cache(DownloadFile cache) {
		if (hasCache(cache)) {
			clear(YSQLites.setParamsToSql("cacheKey='?'", new Object[]{
					cache.getCacheKey()
			}));
		}
		try {
			cache.setCacheTime(System.currentTimeMillis());
			YSQLites.insert(helper, cache);
		} catch (Exception e) {
			Yr.logError(e);
		}
	}

	@Override
	public DownloadFile getCache(YKey key) {

		DownloadFile response = null;
		try {
			List<DownloadFile> downloadFiles = YSQLites.select(helper,
					DownloadFile.class, "cacheKey='?'", new Object[]{key.getKey()});
			if (downloadFiles != null && downloadFiles.size() > 0) {
				response = downloadFiles.get(0);
			}
			if (isOutCacheTime(response)) {
				response = null;
			}
		} catch (Exception e) {
			Yr.logError(e);
		}
		return response;
	}

	@Override
	public Class<?> getBeanClass() {
		return DownloadFile.class;
	}

}
